import 'package:applications/api/applications_api.dart';
import 'package:applications/database/local_db.dart';
import 'package:applications/module/home/po/application_po.dart';
import 'package:applications/utils/image_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:smooth_star_rating_null_safety/smooth_star_rating_null_safety.dart';

/// 下載量最多的免費App 单元格布局
class TopfreeItem extends ConsumerStatefulWidget {
  final int index;
  final ApplicationPo model;

  const TopfreeItem({
    Key? key,
    required this.index,
    required this.model,
  }) : super(key: key);

  @override
  ConsumerState<ConsumerStatefulWidget> createState() => _TopfreeItemState();
}

class _TopfreeItemState extends ConsumerState<TopfreeItem> {
  int _index = 0;
  late ApplicationPo _model;

  @override
  void initState() {
    super.initState();
    _index = widget.index;
    _model = widget.model;
    WidgetsBinding.instance.addPostFrameCallback((_) {
      updateRating(_model.id);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(left: 30.w),
      padding: EdgeInsets.only(
        top: 20.w,
        bottom: 20.w,
        right: 20.w,
      ),
      height: 160.w,
      decoration: const BoxDecoration(
          border: Border(bottom: BorderSide(color: Color(0xFFF0F2F2)))),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Text(
            '$_index',
            style: TextStyle(color: Colors.grey, fontSize: 24.sp),
          ),
          SizedBox(width: 30.w),
          if (_index % 2 != 0)
            Container(
              clipBehavior: Clip.hardEdge,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(20.w),
              ),
              child: loadNetworkImage(
                _model.image,
                width: 120.w,
                height: 120.w,
              ),
            ),
          if (_index % 2 == 0)
            Container(
              clipBehavior: Clip.hardEdge,
              decoration: const BoxDecoration(
                shape: BoxShape.circle,
              ),
              child: loadNetworkImage(
                _model.image,
                width: 120.w,
                height: 120.w,
              ),
            ),
          SizedBox(width: 15.h),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  _model.name,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    fontSize: 30.sp,
                    fontWeight: FontWeight.w500,
                  ),
                ),
                Text(
                  _model.category,
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(color: Colors.grey, fontSize: 24.sp),
                ),
                const Spacer(),
                Row(
                  children: [
                    SmoothStarRating(
                      allowHalfRating: false,
                      starCount: 5,
                      rating: _model.averageUserRating,
                      size: 20.w,
                      defaultIconData: CupertinoIcons.star,
                      filledIconData: CupertinoIcons.star_fill,
                      halfFilledIconData: CupertinoIcons.star_lefthalf_fill,
                      color: Colors.amber.shade400,
                      borderColor: Colors.amber.shade100,
                      spacing: 0.0,
                    ),
                    Text(
                      '(${_model.userRatingCount})',
                      style: TextStyle(color: Colors.grey, fontSize: 18.sp),
                    ),
                  ],
                ),
                SizedBox(height: 10.w),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // 更新评级与评论数
  void updateRating(int id) async {
    // debugPrint('${_model.isFrist}');
    if (_model.isFrist && mounted && id != 0) {
      try {
        // HomeClientCompute.instance.lookup(id: '$id').then((value) {
        //   print("请求成功");
        //   print(value);
        // });
        var response = await ApplicationsAPI().lookup(id: id);
        LocalDb.instance.applicationDao.update(response, _model.id);
        if (mounted) {
          // 将isFrist设置为false, 避免列表重新加载时重复请求api造成api压力
          // 将赋值移到mounted中,防止滑动过快时,未来得及渲染,重新请求刷新
          _model.isFrist = false;
          setState(() {
            _model.averageUserRating = response['averageUserRating'] as double;
            _model.userRatingCount = response['userRatingCount'];
          });
        }
      } catch (e) {
        debugPrint(e.toString());
      }
    }
  }
}
